package cn.harry.component.security.utils;

import cn.harry.component.security.model.SysUserDetails;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * JWT 工具类
 *
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@Component
public class JwtUtils {

    private static StringRedisTemplate redisTemplate;

    @Autowired
    public JwtUtils(StringRedisTemplate redisTemplate) {
        JwtUtils.redisTemplate = redisTemplate;
    }

    /**
     * JWT 加解密使用的密钥
     */
    private static byte[] key;


    /**
     * JWT Token 的有效时间(单位:秒)
     */
    private static int ttl;


    @Value("${security.jwt.key}")
    public void setKey(String key) {
        JwtUtils.key = key.getBytes();
    }

    @Value("${security.jwt.ttl}")
    public void setTtl(Integer ttl) {
        JwtUtils.ttl = ttl;
    }

    /**
     * 权限(角色Code)集合
     */
    private static final String AUTHORITIES = "authorities";

    /**
     * 生成 JWT Token
     *
     * @param authentication 用户认证信息
     * @return Token 字符串
     */
    public static String createToken(Authentication authentication) {
        SysUserDetails userDetails = (SysUserDetails) authentication.getPrincipal();
        Map<String, Object> payload = new HashMap<>();

        // claims 中添加角色信息
        Set<String> roles = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toSet());

        payload.put(AUTHORITIES, roles);

        Date now = new Date();
        // jwt的签发时间
        payload.put(JWTPayload.ISSUED_AT, now);

        // 设置过期时间 -1 表示永不过期
        if (ttl != -1) {
            Date expiration = DateUtil.offsetSecond(now, ttl);
            // jwt的过期时间，这个过期时间必须要大于签发时间
            payload.put(JWTPayload.EXPIRES_AT, expiration);
        }
        // jwt所面向的用户
        payload.put(JWTPayload.SUBJECT, authentication.getName());
        // jwt的唯一身份标识
        payload.put(JWTPayload.JWT_ID, IdUtil.simpleUUID());
        return JWTUtil.createToken(payload, key);
    }

}
